package com.walming.generator.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author walming
 * @date 2020-07-09 13:57
 */
public class IntegerSeriesValidator implements ConstraintValidator<IntegerSeries, Integer> {

    private IntegerSeries series;

    @Override
    public void initialize(IntegerSeries series) {
        this.series = series;
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (value == null || series.list().length <= 0) {
            return true;
        }

        StringBuilder message = new StringBuilder();
        for (int i : series.list()) {
            if (value == i) {
                return true;
            }
            if (message.length() > 0) {
                message.append(",");
            }
            message.append(i);
        }

        // 重置错误提示信息 message
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate("数据不在{" + message + "}集合内").addConstraintViolation();

        return false;
    }

}
